package com.fenger.bus.controller;


import com.fenger.sys.utils.RandomUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("upload")
public class UploadController {

    @Value("${spring.servlet.multipart.location}")
    private String destPath;

    /**
     * 文件上传
     */
    @RequestMapping("uploadFile")
    @ResponseBody
    public Map<String,Object> uploadFile(MultipartFile mf) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> data=new HashMap<>();
        map.put("data", data);
        //得到文件夹名
        String dirName= RandomUtils.createDirNameUserDate();
        //构造文件夹的对象
        File dirFile=new File(destPath+dirName);
        if(!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到文件的新名字
        String newFileName=RandomUtils.createFileNameUseTime(mf.getOriginalFilename());
        File dest=new File(dirFile,newFileName);
        try {
            mf.transferTo(dest);
            map.put("msg", "上传成功");
            map.put("code", 1);
            data.put("src", dirName+"/"+newFileName);
        } catch (IllegalStateException | IOException e) {
            map.put("msg", "上传失败");
            e.printStackTrace();
            map.put("code", -1);
        }
        return map;
    }

    /**
     * 文件或图片下载的方法
     */
    @RequestMapping("downloadFile")
    public ResponseEntity<Object> downloadFile(String path){
        //组装文件对象
        File file=new File(destPath+"/"+path);
        if(file.exists()) {
            //将下载的文件，封装byte[]
            byte[] bytes=null;
            try {
                bytes = FileUtils.readFileToByteArray(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //创建封装响应头信息的对象
            HttpHeaders header=new HttpHeaders();
            //封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置下载的文件的名称
            header.setContentDispositionFormData("attachment", "123.jpg");
            //创建ResponseEntity对象
            ResponseEntity<Object> entity=
                    new ResponseEntity<Object>(bytes, header, HttpStatus.CREATED);

            return entity;
        }
        return null;
    }
}
